# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : running_check.py
# Time       ：2023/8/1 10:28
# Author     ：YangYong
# version    ：python 3.10
# Description：
    运行时检查模块是否存在
    Check whether the module exists at run time
"""
from apis.plugin.models.plugin_manager import PluginManager
from apis.plugin.schema.plugin_manager_schema import PluginManagerSchema
from conf.config import OrderLinesConfig as Config
from orderlines.execute.plugin_manager import PluginFinder
from orderlines.libraries import STANDARD_LIBS
from public.base_model import session_scope


class CheckModule:
    def __init__(self):
        self.modules = dict()
        self.task_module_locations = Config.std_lib_location
        self.class_name = STANDARD_LIBS

    def get_standard_module(self):
        """获取orderlines标准库"""
        for task_module_location in self.task_module_locations:
            modules = PluginFinder(task_module_location, self.class_name)()
            self.modules.update(modules)

    def get_custom_module(self):
        """获取orderlines自定义插件"""
        with session_scope() as session:
            obj = session.query(PluginManager).filter(
                PluginManager.active == 1, PluginManager.enable == 0).all()
        plugin_manager_info = PluginManagerSchema().dump(obj, many=True)
        for item in plugin_manager_info:
            custom_plugin = PluginFinder(item.get('model_name'), [item.get('file_name')])()
            self.modules.update(custom_plugin)

    def get_module(self) -> dict:
        """加载orderlines插件"""
        self.get_standard_module()
        self.get_custom_module()
        return self.modules

    def check_module(self, module_name: str):
        self.get_module()
        if not self.modules.get(module_name):
            raise AttributeError(f'module name {module_name} not find, {self.modules}')
